﻿using Model;
using BLL;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Windows.Forms;
using System.Data;

namespace UI
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        bll_SearchByParameters bll_SearchByParameters = new bll_SearchByParameters();
        ResultClass resultModel = new ResultClass();
        List<DateTime> searchDate = new List<DateTime>();

        DateTime d1 =  Convert.ToDateTime("2023-04-1");
        DateTime d2 = Convert.ToDateTime("2023-04-30");

        private void Form1_Load(object sender, EventArgs e)
        {
            searchDate.Clear();
            searchDate.Add(d1);
            searchDate.Add(d2);

            DataTable dt = new DataTable();
            dgv_ColorBallResult.DataSource = bll_SearchByParameters.SearchByParameters(resultModel, searchDate);


        }



        /// <summary>
        /// 将获取到的JSON数据转换成model类
        /// </summary>
        /// <param name="jsonData"></param>
        /// <returns></returns>
        private static List<ResultClass> AwardDataConvertToModel(dynamic jsonData)
        {
            List<ResultClass> listModels = new List<ResultClass>();
            for (int i = 0; i < jsonData["result"].Count; i++)
            {
                ResultClass model = new ResultClass();
                model.Name = jsonData["result"][i]["name"];
                model.Code = jsonData["result"][i]["code"];
                model.DetailsLink = jsonData["result"][i]["detailsLink"];
                model.VideoLink = jsonData["result"][i]["videoLink"];
                model.AwardDate = jsonData["result"][i]["date"];
                model.AwardWeek = jsonData["result"][i]["week"];
                model.Red = jsonData["result"][i]["red"];
                model.Blue = (int)jsonData["result"][i]["blue"];
                model.Blue2 = string.IsNullOrEmpty(jsonData["result"][i]["blue2"]?.ToString()) ? 0 : int.Parse(jsonData["result"][i]["blue2"].ToString());
                model.Sales = jsonData["result"][i]["sales"];
                model.PoolMoney = jsonData["result"][i]["poolmoney"];
                model.ContentArea = jsonData["result"][i]["content"];
                model.AddMoney = jsonData["result"][i]["addmoney"];
                model.AddMoney2 = jsonData["result"][i]["addmoney2"];
                model.Msg = jsonData["result"][i]["msg"];
                model.Z2Add = jsonData["result"][i]["z2add"];
                model.M2Add = jsonData["result"][i]["m2add"];
                List<PrizeGrade> grades = new List<PrizeGrade>();
                for (int j = 0; j < jsonData["result"][i]["prizegrades"].Count; j++)
                {
                    PrizeGrade model2 = new PrizeGrade();
                    model2.TypeLevel = jsonData["result"][i]["prizegrades"][j]["typelevel"] == null ? 0 : jsonData["result"][i]["prizegrades"][j]["typelevel"];
                    model2.TypeNum = string.IsNullOrEmpty(jsonData["result"][i]["prizegrades"][j]["typenum"]?.ToString()) ? 0 : int.Parse(jsonData["result"][i]["prizegrades"][j]["typenum"].ToString());
                    model2.TypeMoney = jsonData["result"][i]["prizegrades"][j]["typemoney"];
                    grades.Add(model2);
                }
                model.PrizeGrades = grades;
                listModels.Add(model);

            }

            return listModels;
        }

        /// <summary>
        /// 获取开奖数据
        /// </summary>
        /// <param name="content">获取到的开奖数据</param>
        /// <param name="url">用于获取数据的地址</param>
        /// <param name="jsonData">获取到的数据转换成JSON数据</param>
        private static void GetColorBallAwardData(out string content, string url, out dynamic jsonData)
        {
            //创建httpweb请求
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";
            request.Timeout = 800;
            request.Accept = @"text/html,application/xhtml + xml,application/xml; q = 0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7";
            request.CookieContainer = new CookieContainer();
            request.Referer = @"http://www.cwl.gov.cn/ygkj/kjgg/";
            request.UserAgent = @"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36 Edg/112.0.1722.64";
            //创建httpweb响应
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            //获取response的流
            using (Stream receiveStream = response.GetResponseStream())
            {
                //使用streamReader读取数据流
                using (StreamReader sr = new StreamReader(receiveStream, Encoding.UTF8))
                {
                    content = sr.ReadToEnd();
                }
            }
            jsonData = JsonConvert.DeserializeObject(content);
        }

        private void btn_UpdateAwardData_Click(object sender, EventArgs e)
        {
            bll_InsertColorBallAwardData bll = new bll_InsertColorBallAwardData();

            var url = @"http://www.cwl.gov.cn/cwl_admin/front/cwlkj/search/kjxx/findDrawNotice?name=ssq&issueCount=&issueStart=&issueEnd=&dayStart=&dayEnd=&pageNo=1&pageSize=4000&week=&systemType=PC";

            GetColorBallAwardData(out string content, url, out dynamic jsonData);
            List<ResultClass> listModels = AwardDataConvertToModel(jsonData);
            int[] r = new int[2];

            for (int i = 0; i < listModels.Count; i++)
            {
                Guid guid = Guid.NewGuid();
                listModels[i].id = guid;
                listModels[i].PrizeGradeID = guid;
                string[] redNum = listModels[i].Red.Split(',');
                listModels[i].Red1 = Convert.ToInt32(redNum[0]);
                listModels[i].Red2 = Convert.ToInt32(redNum[1]);
                listModels[i].Red3 = Convert.ToInt32(redNum[2]);
                listModels[i].Red4 = Convert.ToInt32(redNum[3]);
                listModels[i].Red5 = Convert.ToInt32(redNum[4]);
                listModels[i].Red6 = Convert.ToInt32(redNum[5]);
                listModels[i].AwardDate = listModels[i].AwardDate.Substring(0, 10);
                string a = bll.InsertColorBallAwardData(listModels[i]);
                Console.WriteLine(a);

            }

            string info = string.Format("更新成功，中奖情怀成功更新{0}条，开奖记录成功更新{1}条", r[0].ToString(), r[1].ToString());
            MessageBox.Show(info);
        }
    }
}
